package com.tuanzi.loan.web.bean.xhh.settlementsystem;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.family.ProductInfo;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementCompany;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementProduct;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementCompanyService;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementIncomeService;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementProductService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.util.XLSUtils;
import com.tuanzi.loan.vo.request.xhh.settlementsystem.XhhSettlementIncomeRequest;
import com.tuanzi.loan.vo.response.xhh.settlementsystem.XhhSettlementIncomeResponse;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.loan.web.lazy.xhh.settlementsystem.XhhSettlementIncomeLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.primefaces.model.LazyDataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;
import static com.tuanzi.loan.business.constants.DictionaryCode.XHH_SETTLEMENT_SPREAD_MODE;

/**
 * @author caiwanlin
 * @create 2018-08-16 20:36
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class XhhSettlementProductInfoBean extends JSFInfoBean<XhhSettlementProduct> {

	private static final String LIST_URL = "/views/xhh/settlementsystem/product-list.xhtml";
	private static final long serialVersionUID = -7377806772057995458L;

	@Autowired
	private XhhSettlementProductService xhhSettlementProductService;

	@Autowired
	private XhhSettlementCompanyService xhhSettlementCompanyService;

	@Autowired
	private XhhSettlementIncomeService xhhSettlementIncomeService;

	private List<ProductInfo> activityList;

	private List<Long> activityIdList;

	private List<XhhSettlementCompany> companyList;

	private XhhSettlementIncomeRequest incomeRequest;

	private LazyDataModel<XhhSettlementIncomeResponse> incomeResponseLazyDataModel;

	private Long originalCompanyId;
	private String originalProductName = "";

	private List<SelectItem> companyGroup;

	@PostConstruct
	private void init() {
		originalCompanyId = new Long(-1);
		String id = getParamFromRequest("id");
		activityList = xhhSettlementProductService.getActivityList();
		companyList = xhhSettlementCompanyService.getCompanyList();
		incomeRequest = new XhhSettlementIncomeRequest();
		if (StringUtils.isNotBlank(id)) {
			$ = xhhSettlementProductService.findOne(Long.parseLong(id));
			originalProductName = $.getProductName();
			originalCompanyId = $.getCompanyId() == null ? originalCompanyId : $.getCompanyId();
			String activityIdStr = $.getActivityIdStr();
			if (StringUtils.isNotBlank(activityIdStr)) {
				String[] split = $.getActivityIdStr().split(",");
				activityIdList = Arrays.stream(split).map(Long::parseLong).collect(Collectors.toList());
			} else {
				activityIdList = Lists.newArrayList();
			}
			// 查询指定产品的消耗记录
			initIncomeLazyDataModel();

		} else {
			activityIdList = Lists.newArrayList();
			$ = new XhhSettlementProduct();
			changeStatusToAdd();
		}

		initCompanyGroup();
	}

	private void initCompanyGroup() {
		companyGroup = Lists.newArrayList();
		Map<String, List<Dictionary>> dicMap = dictionaryService.findAllByCode(XHH_SETTLEMENT_BILLING_PROJECT).stream().collect(Collectors.groupingBy(Dictionary::getValue1));
		companyList.stream().collect(Collectors.groupingBy(XhhSettlementCompany::getBillProject)).forEach((key, value) -> {
			String groupName;
			List<Dictionary> dics = dicMap.get(String.valueOf(key));
			if (null == dics || dics.isEmpty() || null == dics.get(0)) {
				groupName = "其他";
			} else {
				groupName = dics.get(0).getName();
			}
			SelectItemGroup group = new SelectItemGroup(groupName);
			group.setSelectItems(value.stream().map(company -> new SelectItem(company.getId(), company.getCompanyName())).toArray(SelectItem[]::new));
			companyGroup.add(group);
		});
	}

	public String onReturn(String url) {
		return redirect(url, getParam());
	}

	public void initIncomeLazyDataModel() {
		incomeRequest.setProductId($.getId());
		incomeResponseLazyDataModel = new XhhSettlementIncomeLazyDataModel(incomeRequest);
	}

	public void onReset() {
		incomeRequest = new XhhSettlementIncomeRequest();
		initIncomeLazyDataModel();
	}

	public String onSave() {
		if (validate() == false)
			return null;
		String activityIdStr = null;
		ArrayList<Long> temp = new ArrayList<>();
		for (Object a : activityIdList) {
			temp.add(Long.parseLong((String) a));
		}
		activityIdStr = temp.stream().map(String::valueOf).collect(Collectors.joining(","));
		activityIdList = temp;
		$.setActivityIdStr(activityIdStr);
		updateIncomeProductAndCompanyName();
		$ = xhhSettlementProductService.saveOrUpdate($);
		changeStatusToView();
		addSuccessfullyMessage();
		return onReturn(LIST_URL);
	}

	private boolean validate() {
		XhhSettlementProduct dbProduct = xhhSettlementProductService.findByProductName($.getProductName());
		if (null != dbProduct && !dbProduct.getId().equals($.getId())) {
			addErrorMessage("产品名称已存在");
			return false;
		}

		return true;
	}

	private void updateIncomeProductAndCompanyName() {
		if (null != $.getId()) {

			if (!originalProductName.equals($.getProductName())) {
				xhhSettlementIncomeService.updateProductNameByProductId($.getId(), $.getProductName());
			}

			if (!originalCompanyId.equals($.getCompanyId())) {
				XhhSettlementCompany company = xhhSettlementCompanyService.findOne($.getCompanyId());
				xhhSettlementIncomeService.updateCompanyIdAndCompanyNameByCompanyId(originalCompanyId, company.getCompanyName(), company.getId());
			}
		}
	}

	public void onChangeCopMode() {
		$.setPriceCpa(null);
		$.setPriceCps(null);
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(XHH_SETTLEMENT_INCOME_TYPE, XHH_COOPERATION_MODE, XHH_SETTLEMENT_CYCLE, XHH_SETTLEMENT_SPREAD_MODE,
				XHH_SETTLEMENT_SPREAD_CHANNEL);
	}

	public void postProcessXLS(Object doc) {
		HSSFWorkbook wb = (HSSFWorkbook) doc;
		XLSUtils.convertStringToNumeric(wb);
	}
}
